<script setup>
import ListContainer from "@/components/AdminConponents/ListContainer.vue";
import {Search} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {newsDeleteAPI} from "@/api/AdminApi/news.js";
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-message-box.css'
import {ElMessage, ElMessageBox} from "element-plus";
import {ref, computed} from "vue";
import {newsPageAPI} from "@/api/AdminApi/news.js";

const newsList = ref([]) // 新闻列表
const total = ref(0) // 总条数
const loading = ref(false)
const checkList = ref([]) // 选中的分类

// 定义请求参数对象
const params = ref({
  page: 1, // 当前页
  pageSize: 20, // 当前生效的每页条数
  publisherNameOrGameName: null,
  type: null,
  sort: null
})

// 基于params参数，获取新闻列表
const getNewsList = async () => {
  loading.value = true

  const res = await newsPageAPI(params.value)
  newsList.value = res.records
  total.value = res.total

  loading.value = false
}
getNewsList()

// 处理分页逻辑
const onSizeChange = (size) => {
  // console.log('当前每页条数', size)
  // 只要是每页条数变化了，那么原本正在访问的当前页意义不大了，数据大概率已经不在原来的那一页
  // 重新从第一页渲染即可
  params.value.page = 1
  params.value.pageSize = size
  // 基于最新的当前页和每页条数，渲染数据
  getNewsList()
}

const onCurrentChange = (page) => {
  params.value.page = page
  // 基于最新的当前页，渲染数据
  getNewsList()
}

// 选择框改变
const sortChange = () => {
  getNewsList()
}

// 搜索
const search = () => {
  getNewsList()
}

// 计算页数
const totalPages = computed(() => {
  return Math.ceil(total.value / params.value.pageSize)
})

// 上一页
const goToPreviousPage = () => {
  if (params.value.page > 1) {
    params.value.page -= 1;
  }
  getNewsList()
}

// 下一页
const goToNextPage = () => {
  if (params.value.page < totalPages.value) {
    params.value.page += 1;
  }
  getNewsList()
}

// 发行商详细
const router = useRouter()
const handleDetail = (id) => {
  router.push(`/admin/news/detail/${id}`)
}

// 管理员编辑
const handleEdit = (id) => {
  router.push(`/admin/news/edit/${id}`)
}

// 添加管理员
const handleAdd = () => {
  router.push('/admin/news/add')
}

// 删除发行商
const handleDelete = async (id, name) => {
  await ElMessageBox.confirm(`你确认删除${name}发行商吗`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const res = await newsDeleteAPI([id])
  if (res.code === 1) {
    ElMessage.success("删除成功")
    getNewsList()
  } else {
    ElMessage.error(res.msg)
  }
}

// 处理选中的分类
const handleSelectionChange = (val) => {
  checkList.value = val
}

// 批量删除
const deleteBatch = async () => {
  if (checkList.value.length === 0) {
    ElMessage.warning("请选择要删除的发行商！")
    return
  }
  await ElMessageBox.confirm(`你确认删除所选发行商吗，该操作无法撤销`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const ids = checkList.value.map(item => item.id)
  const res = await newsDeleteAPI(ids)
  if (res.code === 1) {
    ElMessage.success("删除成功")
    getNewsList()
  } else {
    ElMessage.error(res.msg)
  }
}
</script>

<template>
  <ListContainer>
    <template #headerLeft>
      <el-input
          v-model="params.publisherNameOrGameName"
          placeholder="请输入开发商或者游戏名称"
          class="input-with-select">
        <template #append>
          <el-button @click="search" :icon="Search" />
        </template>
      </el-input>
      <el-select v-model="params.sort" placeholder="排序方式" @change="sortChange">
        <el-option label="按修改时间" :value="0" />
        <el-option label="按阅读人数" :value="1" />
        <el-option label="按创建日期" :value="2" />
      </el-select>
      <el-select v-model="params.type" placeholder="状态" @change="sortChange">
        <el-option label="所有" :value="0" />
        <el-option label="草稿" :value="1" />
        <el-option label="已发布" :value="2" />
      </el-select>
    </template>
    <template #headerRight>
      <el-button type="danger" @click="deleteBatch" style="width: 100px;">
        <i class="iconfont icon-shanchu"></i>
        批量删除
      </el-button>
      <el-button type="primary" @click="handleAdd" style="width: 110px;">
        <i class="iconfont icon-tianjia"></i>
        新增新闻
      </el-button>
    </template>
    <template #body>
      <el-table
          :data="newsList"
          v-loading="loading"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" class="ellipsis" label="文章标题">
          <template #default="{ row }">
            <el-link @click="handleDetail(row.id)" type="primary" :underline="false">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="publisher" label="发行商名称"/>
        <el-table-column prop="game" label="关联游戏"/>
        <el-table-column prop="view" label="阅读人数"/>
        <el-table-column prop="type" label="新闻状态">
          <template #default="{ row }">
            {{row.type === 0 ? '草稿' : '已发布'}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px">
          <template #default="{ row }">
            <el-button type="success" @click="handleDetail(row.id)" size="small">详细</el-button>
            <el-button type="success" @click="handleEdit(row.id)" size="small">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row.id, row.name)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #footerLeft>
      <el-button
          type="info"
          :disabled="params.page === 1"
          @click="goToPreviousPage">
        上一页
      </el-button>
      <el-button
          type="info"
          :disabled="params.page === totalPages"
          @click="goToNextPage">
        下一页
      </el-button>
    </template>
    <template #footerRight>
      <el-pagination
          v-model:current-page="params.page"
          v-model:page-size="params.pageSize"
          :page-sizes="[5, 10, 20, 40]"
          layout="total, sizes, pager, jumper"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
      />
    </template>
  </ListContainer>
</template>

<style scoped>

</style>
